//
//  XSJStatusPictureView.swift
//  weiBo项目准备
//
//  Created by 鲜世杰 on 16/5/16.
//  Copyright © 2016年 鲜世杰. All rights reserved.
//

import UIKit

private let CZStatusPictureViewCellIdentifier = "CZStatusPictureViewCellIdentifier"
let itemMargin : CGFloat = 5
let itemWidth = (screenWidth - 2 * StatusTableViewCellMargin - 2 * itemMargin) / 3


class XSJStatusPictureView: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegate {
    
    var picUrls : [XSJStatusPictureInfo]?{
    
        didSet {
//            messageLabel.text = "\(picUrls?.count ?? 0)" 
//            messageLabel.text = "\(picUrls?.count ?? 0)"
            
            let currentSize = calcSize(picUrls?.count ?? 0)
            
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(currentSize)
            }
           
            reloadData()
        }
        
    }
    
    
    private func calcSize(count : Int) -> CGSize {
    
//        let itemMargin : CGFloat = 5
//        let itemWidth = (screenWidth - 2 * StatusTableViewCellMargin - 2 * itemMargin) / 3
        let cols = count > 3 ? 3 : count
        let rows = (count - 1) / 3 + 1
        let currentWidth = CGFloat(cols) * itemWidth + CGFloat(cols - 1) * itemMargin
        let currentHeight = CGFloat(rows) * itemWidth + CGFloat(rows - 1)*itemMargin
        return CGSize(width: currentWidth, height: currentHeight)
    }
    
    
    private lazy var messageLabel : UILabel = UILabel(textColor: UIColor.redColor(), fontSize: 20)
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        flowLayout.minimumInteritemSpacing = itemMargin
        flowLayout.minimumLineSpacing = itemMargin
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setupUI () {
    backgroundColor = UIColor.whiteColor()
//        backgroundColor = RandomColor()
        addSubview(messageLabel)
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self)
            
        }
        
        registerClass(XSJStatusPictureViewCell.self, forCellWithReuseIdentifier: CZStatusPictureViewCellIdentifier)
        dataSource = self
        delegate = self
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CZStatusPictureViewCellIdentifier, forIndexPath: indexPath) as! XSJStatusPictureViewCell
//        backgroundColor = RandomColor()
        cell.picInfo = picUrls![indexPath.item]
        return cell
    }
    
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        photoBrowser.currentImageIndex = indexPath.item
        photoBrowser.imageCount = picUrls?.count ?? 0
        //  来源视图
        photoBrowser.sourceImagesContainerView = self
        photoBrowser.show()
        
    }

    
}

extension XSJStatusPictureView: SDPhotoBrowserDelegate {


    
    // 返回临时占位图片（即原来的小图）
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        let cell = self.cellForItemAtIndexPath(indexPath)! as! XSJStatusPictureViewCell
        
        return cell.imageView.image
    }
    // 返回高质量图片的url
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        let urlStr = picUrls![index].thumbnail_pic!.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        return NSURL(string: urlStr)
    }

    

}

class XSJStatusPictureViewCell : UICollectionViewCell {
    var picInfo : XSJStatusPictureInfo?{
    
        didSet {
        
            guard let url = picInfo?.thumbnail_pic else {
            
//                imageView.sd_setImageWithURL(NSURL(string: url), placeholderImage: UIImage(named: "timeline_image_placeholder"))
                return
            }
            
            imageView.sd_setImageWithURL(NSURL(string: url), placeholderImage: UIImage(named: "timeline_image_placeholder"))
            gifImageView.hidden = !url.hasSuffix(".gif")
        }
        
    }
    
    private lazy var imageView : UIImageView = {
    
        let view = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        view.contentMode = UIViewContentMode.ScaleAspectFill
        view.clipsToBounds = true

        
        return view
    }()
    private lazy var gifImageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //  添加控件设置约束
    private func setupUI() {
        contentView.addSubview(imageView)
        contentView.addSubview(gifImageView)
        
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        gifImageView.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(imageView)
            make.bottom.equalTo(imageView)
        }
        
    }

    
}
